﻿package util;

/**
 * ADAMS Engine Core. 
 * Copyright ⓒ 2010 LGHitachi Co., Ltd. All Rights Reserved.
 * 
 * @Program Name : Util.java
 * @Description :
 * 
 * @author Jun
 * @version 1.1 2010. 2. 18. Renewal 작업
 */

import java.io.File;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

//import com.lgh.adams.logging.Logger;

public class Util {

    protected static Util m_instance;
    private static final String _0 = "0";
    private static final String _NULL = "";
    private static final String _COMMA1 = "'";
    private static final String _COMMA2 = "＇";
    private static final String _SPACE = " ";
    private static final String _TWO_SPACE = "　";

    protected Util() {
        m_instance = null;
    }

    /**
     * 기능 : '0'으로 모두 채워진 문자열을 null로 바꾸어줌.
     * 
     * @param str
     *            입력 문자열
     *@return 변경된 문자열
     */
    public static String allZeroToNull(String str) {
        if (str == null) {
            return "";
        } else {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                sb.append('0');
            }

            String newStr = new String(sb);

            if (str.equals(newStr))
                return "";
            else
                return str;
        }
    }

    /**
     * 기능 : String의 길이를 넘어온 문자수로 맞추기위해 Space를 추가하거나 잘라서 보낸다.
     * 
     * @param String
     *            str_org String
     *@param int str_length 문자열 전체 길이
     *@return 정해진 길이로 맞춘 String
     */
    public static String fillSpace(String str_org, int str_length) {
        if (str_length > 0) {
            if (str_org.length() < str_length) {
                StringBuffer sb = new StringBuffer();
                sb.append(str_org);
                for (int i = (str_length - str_org.length()); i > 0; i--) {
                    sb.append(" ");
                }
                str_org = sb.toString();
            } else if (str_org.length() < str_length) {
                str_org = str_org.substring(0, str_length);
            }
            return str_org;
        }
        return "";
    }

    /**
     * 기능 : String의 길이를 넘어온 문자수로 맞추기위해 Space를 앞이나 뒤 지정된위치에 추가하거나 잘라서 보낸다.
     * 
     * @param String
     *            str_org String
     *@param int str_length 문자열 전체 길이
     *@param String
     *            FB (F=앞에 채우기 / B=뒤에 채우기)
     *@return 정해진 길이로 맞춘 String
     */
    public static String fillSpace(String str_org, int str_length, String FB) {
        StringBuffer sb = new StringBuffer();
        if (str_length > 0) {

            if (str_org.length() < str_length) {

                if (FB.equals("B")) { // 뒷쪽에 채우기
                    sb.append(str_org);
                    for (int i = (str_length - str_org.length()); i > 0; i--) {
                        sb.append(" ");
                    }
                } else if (FB.equals("F")) { // 앞쪽에 채우기
                    for (int i = (str_length - str_org.length()); i > 0; i--) {
                        sb.append(" ");
                    }
                    sb.append(str_org);
                }

            } else if (str_org.length() > str_length) {
                sb.append(str_org.substring(0, str_length));
            } else if (str_org.length() == str_length) {
                sb.append(str_org.substring(0, str_length));
            }

            return sb.toString();
        }

        return "";
    }

    /**
     * 기능 : String의 길이를 넘어온 문자수로 맞추기위해 0을 추가하거나 잘라서 보낸다.
     * 
     * @param String
     *            str_org String
     *@param int str_length 문자열 전체 길이
     *@return 정해진 길이로 맞춘 String
     */
    public static String fillZero(String str_org, int str_length) {
        StringBuffer sb = new StringBuffer();
        int zero_len = str_length - str_org.length();

        if (zero_len > 0) {
            for (int i = 0; i < zero_len; i++) {
                sb.append(_0);
            }
        }
        sb.append(str_org);

        return sb.toString();
    }

    public static void PrintAlertErrorMsg(PrintWriter printwriter, String s,
            String s1) {
        boolean _tmp = s.equals("") || s == null;
        printwriter.println("<SCRIPT LANGUAGE=\"JavaScript\">");
        printwriter.println("\tfunction " + s1 + "()");
        printwriter.println("\t{");
        printwriter.println("\t\talert(\"" + s + "\");");
        printwriter.println("\t\treturn;");
        printwriter.println("\t}");
        printwriter.println("\t" + s1 + "();");
        printwriter.println("</SCRIPT>");
    }

    public static String getConvertFileName(String s, String s1) {
        if (s == null || s.length() <= 0) {
            return "";
        }
        if (s1 == null || s1.length() <= 0) {
            return s;
        }
        int i = s.lastIndexOf(File.separatorChar);
        String s2 = s.substring(0, i);
        String s3 = "";
        String s4 = "";
        i = s.lastIndexOf(".");
        if (i != -1) {
            s4 = s.substring(i);
        }
        i = s1.lastIndexOf(".");
        if (i != -1) {
            return s2 + File.separatorChar + s1;
        } else {
            return s2 + File.separatorChar + s1 + s4;
        }
    }

    public static Util getInstance() throws Exception {
        if (m_instance == null) {
            throw new Exception(
                    "System is not initialized properly: Util instance is null");
        } else {
            return m_instance;
        }
    }

    public static String getNextStringTypePK(String s) {
        try {
            if (s == null || s.length() < 0) {
                return "";
            }
            new String();
            String s1 = String.valueOf(Long.parseLong(s) + 1L);
            String s2 = "";
            for (int i = 0; i < s.length(); i++) {
                s2 = s2 + "0";

            }
            return (s2 + s1).substring(s1.length());
        } catch (Exception ex) {
            return "Invalid Parameter";
        }
    }

    public static String getNextStringTypePK(String s, String s1) {
        try {
            if (s == null) {
                s = "";
            }
            if (s1 == null || s1.length() <= s.length()) {
                return "";
            }
            new String();
            String s2 = String
                    .valueOf(Long.parseLong(s1.substring(s.length())) + 1L);
            String s3 = "";
            for (int i = 0; i < s1.length() - s.length(); i++) {
                s3 = s3 + "0";

            }
            return s + (s3 + s2).substring(s2.length());
        } catch (Exception ex) {
            return "Invalid Parameter";
        }
    }

    public static long getTimeInterval(String s, String s1, int i) {
        if (s.length() < 14 || s1.length() < 14) {
            return 0L;
        }
        Calendar calendar = Calendar.getInstance();
        Calendar calendar1 = Calendar.getInstance();
        calendar.set(Integer.parseInt(s.substring(0, 4)), Integer.parseInt(s
                .substring(4, 6)), Integer.parseInt(s.substring(6, 8)), Integer
                .parseInt(s.substring(8, 10)), Integer.parseInt(s.substring(10,
                12)), Integer.parseInt(s.substring(12, 14)));
        calendar1.set(Integer.parseInt(s1.substring(0, 4)), Integer.parseInt(s1
                .substring(4, 6)), Integer.parseInt(s1.substring(6, 8)),
                Integer.parseInt(s1.substring(8, 10)), Integer.parseInt(s1
                        .substring(10, 12)), Integer.parseInt(s1.substring(12,
                        14)));
        Date date = calendar.getTime();
        Date date1 = calendar1.getTime();
        long l = date.getTime() - date1.getTime();
        switch (i) {
        case 13: /* '\r' */
            l /= 1000L;
            break;

        case 12: /* '\f' */
            l = l / 1000L / 60L;
            break;

        case 10: /* '\n' */
            l = l / 1000L / 60L / 60L;
            break;

        case 5: /* '\005' */
            l = l / 1000L / 60L / 60L / 24L;
            break;

        }
        return l;
    }

    public static String[] getToken(String s, String s1) {
        if (s == null || s.length() < 0) {
            s = "";
        }
        if (s1 == null || s1.length() < 0) {
            s1 = "";
        }
        StringTokenizer stringtokenizer = new StringTokenizer(s, s1);
        String as[] = new String[stringtokenizer.countTokens()];
        for (int i = 0; stringtokenizer.hasMoreTokens(); i++) {
            as[i] = stringtokenizer.nextToken();

        }
        return as;
    }

    public static String[] getToken(String s, String s1, int i) {
        if (s == null || s.length() < 0) {
            s = "";
        }
        if (s1 == null || s1.length() < 0) {
            s1 = "";
        }
        StringTokenizer stringtokenizer = new StringTokenizer(s, s1);
        String as[] = new String[i];
        int j = stringtokenizer.countTokens();
        for (int k = 0; k < as.length; k++) {
            if (k >= j) {
                as[k] = "";
            } else {
                as[k] = stringtokenizer.nextToken();

            }
        }
        return as;
    }

    public static void init() throws Exception {
        if (m_instance == null) {
            m_instance = new Util();
        }
    }

    public static String itos(int i) {
        return new Integer(i).toString();
    }

    public static String ltos(long l) {
        return new Long(l).toString();
    }

    public static String makeMoneyType(int i, String s) {
        String s1 = new Integer(i).toString();
        DecimalFormat decimalformat = new DecimalFormat();
        DecimalFormatSymbols decimalformatsymbols = new DecimalFormatSymbols();
        decimalformatsymbols.setGroupingSeparator(s.charAt(0));
        decimalformat.setGroupingSize(3);
        decimalformat.setDecimalFormatSymbols(decimalformatsymbols);
        return decimalformat.format(Double.parseDouble(s1)).toString();
    }

    public static String makeMoneyType(int i, String s, int j) {
        String s1 = new Integer(i).toString();
        DecimalFormat decimalformat = new DecimalFormat();
        DecimalFormatSymbols decimalformatsymbols = new DecimalFormatSymbols();
        decimalformatsymbols.setGroupingSeparator(s.charAt(0));
        decimalformat.setGroupingSize(j);
        decimalformat.setDecimalFormatSymbols(decimalformatsymbols);
        return decimalformat.format(Double.parseDouble(s1)).toString();
    }

    public static String makeMoneyType(String s, String s1) {
        if (s == null) {
            return "0";
        } else {
            DecimalFormat decimalformat = new DecimalFormat();
            DecimalFormatSymbols decimalformatsymbols = new DecimalFormatSymbols();
            decimalformatsymbols.setGroupingSeparator(s1.charAt(0));
            decimalformat.setGroupingSize(3);
            decimalformat.setDecimalFormatSymbols(decimalformatsymbols);
            return decimalformat.format(Double.parseDouble(s)).toString();
        }
    }

    public static String makeMoneyType(String s, String s1, int i) {
        if (s == null) {
            return "0";
        } else {
            DecimalFormat decimalformat = new DecimalFormat();
            DecimalFormatSymbols decimalformatsymbols = new DecimalFormatSymbols();
            decimalformatsymbols.setGroupingSeparator(s1.charAt(0));
            decimalformat.setGroupingSize(i);
            decimalformat.setDecimalFormatSymbols(decimalformatsymbols);
            return decimalformat.format(Double.parseDouble(s)).toString();
        }
    }

    public static String makeNoMoneyType(String s, String s1) {
        if (s == null) {
            return "0";
        }
        StringTokenizer stringtokenizer = new StringTokenizer(s, s1);
        String s2 = "";
        Object obj = null;
        while (stringtokenizer.hasMoreTokens()) {
            String s3 = stringtokenizer.nextToken();
            s2 = s2 + s3;
        }

        return s2;
    }

    protected static String makeTowDigit(int i) {
        return (i >= 10 ? "" : "0") + i;
    }

    public static String parsePostString(String s, String s1) {
        s = s + "&";
        s1 = s1 + "=";
        int i = s.indexOf(s1, 0);
        if (i == -1) {
            return "";
        }
        i += s1.length();
        int j = s.indexOf("&", i);
        if (j < i + 1) {
            return "";
        } else {
            return s.substring(i, j);
        }
    }

    public static String parseQueryString(String s, String s1) {
        s = s + "&";
        s1 = s1 + "=";
        int i = s.indexOf(s1, 0);
        if (i == -1) {
            return "";
        }
        i += s1.length();
        int j = s.indexOf("&", i);
        if (j < i + 1) {
            return "";
        }
        String s2 = s.substring(i, j);
        for (int k = s2.indexOf("%20"); k != -1; k = s2.indexOf("%20")) {
            s2 = s2.substring(0, k) + " " + s2.substring(k + 3, s2.length());

        }
        return s2;
    }

    public static String quote(String s) {
        if (s == null) {
            return "''";
        } else {
            return "'" + s + "'";
        }
    }

    public static void saveAsFileName(String s, String s1) throws Exception {
        try {
            if (!new File(s).renameTo(new File(s1))) {
                throw new Exception();
            }
        } catch (Exception ex) {
            throw new Exception();
        }
    }

    public static int stoi(String s) {
        if (s == null) {
            return 0;
        } else {
            try {
                return Integer.valueOf(s).intValue();
            } catch (Exception e) {
                return 0;
            }
        }
    }
    public static int stoi(String s, int _default) {
        if (s == null) {
            return _default;
        } else {
            try {
                return Integer.valueOf(s.trim()).intValue();
            } catch (Exception e) {
                return _default;
            }
        }
    }
    
    public static float stof(String s){
        if (s == null || s == "") {
            return 0F;
        } else {
            return Float.valueOf(s).floatValue();
        }
    }

    public static long stol(String s) {
        if (s == null || s == "") {
            return 0L;
        } else {
            return Long.valueOf(s).longValue();
        }
    }

    public static String NVL(String str) {
        if (str == null) {
            return "";
        } else {
            return str;
        }
    }
    
    public static String NVLtrim(String str) {
        if (str == null) {
            return "";
        } else {
            return str.trim();
        }
    }

    /**
     * 입력받은 double형을 원하는 원하는 문자열 포맷으로 변경시켜 준다.
     * 
     * @param num
     *            입력받은 double
     * @param form
     *            입력받은 format
     * @return String 포맷변경된 String
     */
    public static String dFormat(double num, String form) {
        DecimalFormat decimalformat = new DecimalFormat(form);
        return decimalformat.format(num);
    }

    /**
     * 입력받은 double형을 원하는 원하는 문자열 포맷으로 변경시켜 준다.
     * 
     * @param num
     *            입력받은 BigDecimal
     * @param form
     *            입력받은 format
     * @return String 포맷변경된 String
     */
    public static String dFormat(BigDecimal num, String form) {
        DecimalFormat decimalformat = new DecimalFormat(form);
        return decimalformat.format(num);
    }

    public static String dFormat(String num, int i) {

        return dFormat(stod(num), i);
    }

    public static String dFormat(String num) {

        return dFormat(stod(num), 0);
    }

    public static String dFormat(double d, int i) {
        StringBuffer sb = new StringBuffer();
        sb.append("#,##0");
        if (i > 0) {
            sb.append(".");
        }
        for (int j = 0; j < i; j++) {
            if (j == 0) {
                sb.append("0");
            } else {
                sb.append("#");
            }
        }

        DecimalFormat decimalformat = new DecimalFormat(sb.toString());
        return decimalformat.format(d);
    }

    /**
     * String을 double값으로 변환한다. <BR>
     * int cnt = ComUtil.stod("10"); <BR>
     * 
     * @param str
     *            double값으로 변환될 String문자열.
     * @return 변환된 int 값.
     */
    public static double stod(String str) {
        if (str == null) {
            return 0;
        }
        try {
            return (Double.parseDouble(str));
        } catch (java.lang.NumberFormatException e) {
            return 0L;
        }
    }

    /**
     * String 문자열을 BigDecimal타입으로 형변환
     * 
     * @param BigDecimal타입으로
     *            변환될 문자열
     * @return 변환된 BigDecimal 값.
     */
    public static BigDecimal strToBigDecimal(String str) {
        if (str == null) {
            return new BigDecimal(0);
        }
        try {
            return (new BigDecimal(str));
        } catch (java.lang.NumberFormatException e) {
            return new BigDecimal(0);
        }
    }

    /**
     * int값을 String으로 변환한다. <BR>
     * 예) Strint str = ComUtil.dtos(10); <BR>
     * 
     * @param i
     *            String으로 변환될 int 값.
     * @return 변환된 String 값.
     */
    public static String dtos(double i) {
        return (new Double(i).toString());
    }

    public static String CUT(String s, int idx, int length) {
        if (s == null) {
            return "";
        }
        try {
            return s.substring(idx, idx + length);
        } catch (Exception e) {
            return "";
        }
    }

    public static String CUT(byte[] b, int idx, int length) {
        String s = "";

        if (b == null) {
            s = "";
        }
        try {
            s = (new String(b, idx, length, "KSC5601"));
            if (s.length() > 1) {
                if ((s.substring(0, 1)).equals("+")) {
                    s = s.substring(1);
                } else {
                    s = s.substring(0);
                }
            }
        } catch (Exception e) {
            s = "";
        }

        return s;
    }

    public static String substr(String str, int offset, int endIndex) {
        if (str == null || _NULL.equals(str))
            return _NULL;
        try {
            return str.substring(offset, endIndex);
        } catch (Exception e) {
//            Logger.error("EUT21001", str, e.getMessage());	//Logger.error("SUBSTRING ERROR => VALUE : [" + str + "], ERROR MSG => " + e.getMessage());
            return str;
        }
    }

    public static String substr2(String str, int offset, int length) {

        if (str == null || _NULL.equals(str))
            return _NULL;
        try {
            return str.substring(offset, offset + length);
        } catch (Exception e) {
//            Logger.error("EUT21002", str, e.getMessage());	//Logger.error("SUBSTRING ERROR => VALUE : [" + str + "], ERROR MSG => " + e.getMessage());
            return str;
        }

    }

    public static String substr(String str, int offset) {
        if (str == null || _NULL.equals(str))
            return _NULL;

        try {
            return str.substring(offset);
        } catch (Exception e) {
//            Logger.error("EUT21003", str, e.getMessage());	//Logger.error("SUBSTRING ERROR => VALUE : [" + str + "], ERROR MSG => " + e.getMessage());
            return str;
        }
    }

    public static String replace(String str) {
        if (str != null && !_NULL.equals(str)) {
            try {

                return ((str.replaceAll(_COMMA1, _SPACE)).replaceAll(_COMMA2,
                        _SPACE)).replaceAll(_TWO_SPACE, _SPACE);
            } catch (Exception e) {
//                Logger.error("EUT21004", str, e.getMessage());	//Logger.error("REPLACE ERROR => VALUE : [" + str + "] " + e.getMessage());
                return str;
            }
        } else {
            return _NULL;
        }
    }

    /**
     *기능 : 문자열에서 일정한부분을 다른 문자열로 치환 <br>
     * 
     * @param word
     *            string
     * @param fromStr
     *            string
     * @param toStr
     *            string
     * @return 새로운 string
     */
    public static String replaceString(String word, String fromStr, String toStr) {
        // word가 null인 경우
        if (word == null)
            return "";

        if (word.equals(""))
            return "";

        StringBuffer result = new StringBuffer(100);

        int start = 0;
        int hit = 0;

        String strUpper = word.toUpperCase();
        String searchUpper = fromStr.toUpperCase();

        while ((hit = strUpper.indexOf(searchUpper, start)) != -1) {
            result.append(word.substring(start, hit)).append(toStr);
            start = hit + fromStr.length();
        }

        result.append(word.substring(start));

        return result.toString();
    }

    
    /*
     * 기능 : 첫번째 인자값이 두번째 이상 인자에 같은 값이 있으면 TRUE 없으면 FALSE
     */
    public static boolean IN(String value, String[] args) {

        if (args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                if (value.equals(args[i]))
                    return true;
            }

        }
        return false;
    }

    
    
    /**
     * 
     * @param str
     * @param length
     * @param ch
     * @param leftAlign
     * @return
     */
    public static String fixLength(String str, int length, char ch, boolean leftAlign) {
        
        str = (str == null) ? "" : str;

        byte[] newBytes = new byte[length];
        byte[] strBytes = str.getBytes();
        int len = strBytes.length;

        if(len == length) {
            return str;
        }

        byte chByte = (byte)ch;
        if(len > length) {
            System.arraycopy(strBytes, 0, newBytes, 0, length);
        } else {
            if(leftAlign) {
                System.arraycopy(strBytes, 0, newBytes, 0, len);
                for(int i = len; i < length; i++) {
                    newBytes[i] = chByte;
                }
            } else {
                int temp = length - len;
                for(int i = 0; i < temp; i++) {
                    newBytes[i] = chByte;
                }
                System.arraycopy(strBytes, 0, newBytes, temp, len);
            }
        }

        return new String(newBytes);
    }    
    
    
    /**
     * Object의 class address를 줄여 반환
     * @param data
     * @return
     */
    public static String getClassAddress(Object data) {
    	String[] datas = ("" + data).split("[.]");
    	return datas[datas.length - 1];
    }
		

}
